using System;
using System.Diagnostics;
using System.Drawing;
using System.Net.NetworkInformation;
using System.ServiceModel;
using System.Windows.Forms;

using Microsoft.Services.TfsAlert.AppCode;
using Microsoft.Services.TfsAlert.AppCode.NotificationEvents;
using Microsoft.Services.TfsAlert.Core;
using Microsoft.Services.TfsAlert.Core.BusinessFacades;
using Microsoft.Services.TfsAlert.Core.BusinessFacades.RegistrationBF;
using Microsoft.Services.TfsAlert.UIControl;


namespace Microsoft.Services.TfsAlert.Forms
{
    public partial class main : Form
    {
        private Icon _baseIcon;
        private Icon _yellowIcon;
        private Icon _redIcon;
        private IRegistrationManager _registrationManager;

        public main()
        {
            InitializeComponent();

            _baseIcon = getIcon( "tfs_alerts_16.ico" );
            _yellowIcon = getIcon("tfs_alerts_16_warning.ico");
            _redIcon = getIcon("tfs_alerts_16_failed.ico");

            NotificationReciever.MessageAlert += ( new MessageAlertDelegate( this.TFSMessage ) );
            Application.ApplicationExit += ( new EventHandler( this.applicationExit ) );
            NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkAvailabilityChangedCallback);

            ApplicationHelpers applicationHelpers = new ApplicationHelpers();

            try
            {
                //Register the Selected TFS Events
                IBusinessFacadeFactory _businessFacadeFactory = BusinessFacadeFactory.CreateInstance();
                IRegistrationFactory _regFactory = _businessFacadeFactory.CreateRegistrationManager();
                _registrationManager = _regFactory.CreateRegistrationManager();
                _registrationManager.Suscribe();
            }
            catch( Exception ex )
            {
                if( Instrumentation.GeneralTraceSwitch.TraceError )
                {
                    Trace.TraceError( ex.Message );
                }

                trayNotify.ShowBalloonTip( 3, "Startup | TFSAlert",
                                           "Exception, please see event log for more information", ToolTipIcon.Error );
                return;
            }

            trayNotify.ShowBalloonTip( 3, "Startup | TFSAlert", "Successful", ToolTipIcon.Info );
        }

        #region Application Events

        private void TFSMessage( object sender, MessageAlertEventArgs e )
        {
            if (smartIcons.Checked)
                this.trayNotify.Icon = _yellowIcon;

            trayNotify.ShowBalloonTip( 3, e.NotificationEventMessageTitle + " | TFSAlert", e.NotificationEventMessageBody, ToolTipIcon.Info );
        }

        internal void applicationExit( object source, EventArgs e )
        {
            //UnRegister the Selected TFS Events
            _registrationManager.UnSuscribe();

            //TODO: this should be moved someplace more global
            //TfsAlert.ServiceHost.Close();
        }

        internal void NetworkAvailabilityChangedCallback(object sender, EventArgs e)
        {
            this.TFSMessage(null, new MessageAlertEventArgs(new GenericEvent("Network Change", "Network Change, Updating TFS subscriptions")));

            //ReSubscribe
            NetworkInterface[] interfaceAdapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface networkInterface in interfaceAdapters)
            {
                if ( OperationalStatus.Up == networkInterface.OperationalStatus &&
                     NetworkInterfaceType.Loopback != networkInterface.NetworkInterfaceType &&
                     NetworkInterfaceType.Tunnel != networkInterface.NetworkInterfaceType )
                {
                    _registrationManager.Suscribe();
                    break;
                }
            }
        }

        #endregion //Application Events

        #region Context Menu and Click Events

        private void aboutToolStripMenuItem_Click( object sender, EventArgs e )
        {
            about aboutForm = new about();
            aboutForm.Show();
        }

        /// <summary>
        /// Exit and Close This Application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitToolStripMenuItem_Click( object sender, EventArgs e )
        {
            Application.Exit();
        }

        /// <summary>
        /// Swap the icon back to base icon ( all messages read ) when the icon is clicked on
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trayNotify_MouseClick( object sender, MouseEventArgs e )
        {
            this.trayNotify.Icon = _baseIcon;
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ApplicationSettingsController controller = new ApplicationSettingsController();

            controller.Show();

            //ApplicationSettings appSettingsForm = new ApplicationSettings();
            //appSettingsForm.Show();
        }

        #endregion //Context Menu and Click Events

        /// <summary>
        /// Retrieves an icon (marked as an embedded resource).
        /// </summary>
        /// <param name="iconName">The name of the icon.</param>
        /// <returns>The request icon.</returns>
        private Icon getIcon( string iconName )
        {
            return new Icon( this.GetType(), iconName );
        }
    }
}